package cn.lyvust.shili03;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.*;
import java.awt.*;

public class Lkcalculator03 extends JFrame {
    // 创建一个 ScriptEngine对象 用于将字符串计算式转化为结果
    private ScriptEngine se = new ScriptEngineManager().getEngineByName("JavaScript");
    private JTextField jisuan_text = new JTextField();
    private JTextField answer_text = new JTextField();

    public Lkcalculator03() {
        this.setTitle("简易计算器v1.0");
        this.setBounds(100, 100, 500, 550);
        this.setLabel();
        this.setBtn();
        this.setCopyRight();
        this.getContentPane().setLayout(null);
//        this.getContentPane().setBackground(Color.BLUE);
        this.setLayout(null);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new Lkcalculator03();
    }
    private void setLabel() {
        // 计算式标签
        JLabel jisuan = new JLabel("计算式");
        jisuan.setFont(new Font("华文楷体", Font.CENTER_BASELINE, 25));
        jisuan.setBounds(20, 0, 80, 80);
        this.getContentPane().add(jisuan);
        // 计算式显示框
        jisuan_text.setBounds(100, 15, 300, 50);
        jisuan_text.setHorizontalAlignment(JTextField.LEFT);
        jisuan_text.setFont(new Font("华文楷体", Font.PLAIN, 20));
        this.getContentPane().add(jisuan_text);

        // 结果标签
        JLabel answer = new JLabel("结  果");
        answer.setFont(new Font("华文楷体", Font.CENTER_BASELINE, 25));
        answer.setBounds(20, 55, 80, 80);
        this.getContentPane().add(answer);
        // 结果显示框
        answer_text.setBounds(100, 70, 300, 50);
        answer_text.setHorizontalAlignment(JTextField.LEFT);
        answer_text.setFont(new Font("华文楷体", Font.PLAIN, 20));
        this.getContentPane().add(answer_text);
    }
    private void setBtn() {
        // 按钮文本
        String[] arr =
                { "del",  "cls", "%",  "/",
                   "7",   "8",   "9",  "*",
                   "4",   "5",   "6",  "+",
                   "1",   "2",   "3",  "-",
                   "+/-", "0",   ".",  "=",
                };
        // 按钮
        JButton[] btnArray = new JButton[arr.length];
        // 创建面板
        JPanel panel = new JPanel();
        // 设置面板的布局方式
        panel.setBounds(20, 150, 400, 300);
        // 网格布局 五行四列
        panel.setLayout(new GridLayout(5, 4, 8, 8));
        for(int i = 0; i < btnArray.length; i++) {
            // 创建按钮
            btnArray[i] = new JButton(arr[i]);
            // 设置按钮字体
            btnArray[i].setFont(new Font("黑体", Font.CENTER_BASELINE, 20));
            // 设置按钮背景颜色
            btnArray[i].setBackground(new Color(242, 240, 235));
            // 设置 = 号的特殊颜色
            if(btnArray.length - 1 == i) {
                btnArray[i].setBackground(new Color(211, 120, 129));
            }
            btnArray[i].addActionListener(e -> {
                String btnValue = e.getActionCommand();
                //退格按钮
                if (btnValue.equals("cls")) {
                    jisuan_text.setText(jisuan_text.getText().length() != 0
                            ? jisuan_text.getText().substring(0, jisuan_text.getText().length() - 1) : "");
                } else if (btnValue.equals("del")) { // 清除按钮
                    jisuan_text.setText("");
                } else if (btnValue.equals("+")) {
                    jisuan_text.setText(m1(jisuan_text, "+"));
                } else if (btnValue.equals("-")) {
                    jisuan_text.setText(m1(jisuan_text, "-"));
                } else if (btnValue.equals("*")) {
                    jisuan_text.setText(m1(jisuan_text, "*"));
                } else if (btnValue.equals("/")) {
                    jisuan_text.setText(m1(jisuan_text, "/"));
                } else if (btnValue.equals("=")) {
                    answer_text.setText(clc(jisuan_text.getText()));
                } else if (btnValue.equals("+/-")) {
                    String txt = jisuan_text.getText().substring(jisuan_text.getText().length()-1, jisuan_text.getText().length());
                    txt = txt.indexOf('-') < 0 ? "-" + txt : "+" + txt;
                    System.out.println(txt);
                } else if ("0123456789".indexOf(btnValue) != -1){ // 0-9数字按钮
                    jisuan_text.setText(jisuan_text.getText() + btnValue);
                }
            });
            // 按钮添加到面板
            panel.add(btnArray[i]);
        } //end for
        this.add(panel);
    } // end setBtn

    /**
     * 获取字符串计算式转化为结果
     * https://blog.csdn.net/m0_38000828/article/details/80975530
     */
    private String clc(String text) {
        Object obj = null;
        try {
            obj = se.eval(text);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        return obj.toString();
    }

    /**
     * 运算表达式里面只出现一次运算符
     */
    private String m1(JTextField jisuan_text, String string) {
        String Str = jisuan_text.getText() + ((jisuan_text.getText().endsWith("+")
                || (jisuan_text.getText().endsWith("-")) || (jisuan_text.getText().endsWith("*"))
                || (jisuan_text.getText().endsWith("/")) || (jisuan_text.getText().endsWith("."))) ? "" : string);
        return Str;

    }

    private void setCopyRight() {
        // 标签
        JLabel label = new JLabel();
        label.setText("<html><span style='font-size:14px;color:red;font-family:宋体'>版权所有：临沂科技职业学院</span></html>");
        label.setBounds(40, 460, 300, 40);
        this.add(label);
    }
}
